<template>
  <el-dialog
    v-model="visible"
    v-if="load"
    :title="form.id ? '修改' : '新增'"
    width="600"
    draggable
    @close="close"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :z-index="2000"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-align="right"
      label-width="85"
      size="default"
      label-position="top"
    >
      <el-row :gutter="21">
        <el-col :span="16">
          <el-form-item label="标签名称" prop="tag_name">
            <el-input
              v-model="form.tag_name"
              placeholder="请输入、最多十个汉字"
              maxlength="10"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="标签状态">
            <el-switch
              v-model="form.tag_status"
              :active-value="1"
              :inactive-value="2"
              active-text="启用"
              inactive-text="禁用"
              inline-prompt
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="标签类型" prop="tag_type">
            <el-select
              v-model="form.tag_type"
              placeholder="请选择"
              class="w-full"
              @change="changeType"
            >
              <el-option
                v-for="item in options['assignment.ImagesTag']?.[0].tagTypeText"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="24" v-if="form.tag_type == 2">
          <el-form-item>
            <span class="font-bold flex items-center" slot="label">
              自动关联
              <el-tooltip
                effect="dark"
                content="用于关联特定状态，自动匹配标签:例如图片任务等级、类型"
                placement="top-start"
              >
                <el-icon>
                  <QuestionFilled />
                </el-icon>
              </el-tooltip>
              <el-switch
                class="ml-2"
                v-model="form.is_auto_relation"
                :active-value="1"
                :inactive-value="0"
                active-text="启用"
                inactive-text="禁用"
                inline-prompt
              />
            </span>
            <template v-if="form.is_auto_relation">
              <el-select
                class="w-full mb-2"
                v-model="form.auto_relation.rule_type"
                placeholder="角色类型"
                clearable
              >
                <el-option
                  :label="item.label"
                  :value="item.value"
                  v-for="(item, index) in options['assignment.ImagesTag']?.[0]
                    .ruleTypeText"
                  :key="index"
                ></el-option>
              </el-select>
              <div class="flex w-full">
                <el-select
                  class="mr-2 flex-1"
                  v-model="form.auto_relation.task_level"
                  placeholder="请选择任务等级"
                  clearable
                >
                  <el-option
                    :label="item.label"
                    :value="item.value"
                    v-for="(item, index) in options['assignment.ImagesAssignment']?.[0]
                      .taskPriorityText"
                    :key="index"
                  ></el-option>
                </el-select>
                <SelectTaskType
                  class="flex-1"
                  v-model="form.auto_relation.task_type"
                  placeholder="请选择任务类型"
                  clearable
                ></SelectTaskType>
                <!-- <el-select
                  class="flex-1"
                  v-model="form.auto_relation.task_type"
                  placeholder="请选择任务类型"
                  clearable
                  collapse-tags-tooltip
                >
                  <el-option
                    :label="item.label"
                    :value="item.value"
                    v-for="(item, index) in options['assignment.ImagesAssignment']?.[0]
                      .taskTypeText"
                    :key="index"
                  ></el-option>
                </el-select> -->
              </div>
              <el-checkbox
                v-model="form.matching_sku_count"
                :true-label="1"
                :false-label="0"
                size="large"
                >按任务SKU数匹配标签数量</el-checkbox
              >
            </template>
          </el-form-item>
        </el-col>
        <el-col :span="12" v-if="form.tag_type == 1 || form.tag_type == 2">
          <el-form-item>
            <span class="font-bold" slot="label">
              分值
              <el-tooltip
                effect="dark"
                content="此分值为图片任务绩效统计使用，根据标签统计图片或任务分值，不同部门使用绩效模式不一样，此处请根据部门实际情况填写。"
                placement="top-start"
              >
                <el-icon>
                  <QuestionFilled />
                </el-icon>
              </el-tooltip>
            </span>
            <el-input
              v-model="form.score"
              placeholder="请输入"
              oninput="value=value.replace(/[^\d.]/g,'').replace(/^(\d*\.?\d{0,2}).*/,'$1')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12" v-if="form.tag_type == 4">
          <el-form-item label="任务类型ID" required>
            <el-input
              v-model="form.image_task_type_id"
              placeholder="请输入"
              oninput="value=value.replace(/[^0-9]/g,'')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12" v-if="form.tag_type == 3">
          <el-form-item label="语言选择">
            <SelectLanguage
              class="w-full"
              v-model="form.language_id"
              @change="changeLanguage"
            ></SelectLanguage>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="标签权限" prop="permissions_type">
            <el-radio-group
              v-model="form.permissions_type"
              class="mr-4"
              @change="changePermissionsType"
            >
              <el-radio :label="1" size="large">所有人</el-radio>
              <el-radio :label="2" size="large">指定人员</el-radio>
              <el-radio :label="3" size="large">指定部门</el-radio>
            </el-radio-group>
            <select-personnel
              v-if="form.permissions_type == 2"
              class="w-full"
              v-model="form.images_tag_permissions"
              placeholder="请选择"
              :multiple="true"
              @change="changePerson"
            ></select-personnel>
            <SelectDepartment
              class="w-full"
              v-model="form.depart_ids"
              placeholder="请选择"
              :multiple="true"
              :checkStrictly="false"
              :emitPath="true"
              v-if="form.permissions_type == 3"
            ></SelectDepartment>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="标签颜色" prop="color">
            <el-radio-group v-model="form.tag_color" class="label-color">
              <el-radio
                v-for="(d, i) in options['assignment.ImagesTag']?.[0].tagColorText"
                :key="i"
                :label="d.value"
                class="m-0"
              >
                <div class="relative w-5 h-5">
                  <div
                    v-if="form.tag_color === d.value"
                    class="absolute w-5 h-5 rounded-xl inset-0 z-0"
                    :style="{ backgroundColor: '#3487FF' }"
                  ></div>
                  <div
                    class="absolute w-4 h-4 rounded-xl border border-white"
                    style="left: 2px; top: 2px"
                    :style="{ backgroundColor: d.value }"
                  ></div>
                </div>
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="排序">
            <el-input
              v-model="form.sort"
              placeholder="请输入"
              oninput="value=value.replace(/[^0-9]/g,'')"
              clearable
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="备注">
        <el-input
          v-model="form.remark"
          placeholder="请输入备注"
          type="textarea"
          :autosize="{ minRows: 4, maxRows: 6 }"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="close">取 消</el-button>
      <el-button type="primary" :loading="loading" @click="save(formRef)"
        >保 存</el-button
      >
    </template>
  </el-dialog>
</template>
<script setup name="ComModal">
import { createImagesTag, editImagesTag, getImagesTagDetail } from "../api";
import { reactive, toRefs } from "vue";
import { ElMessage } from "element-plus";
import SelectDepartment from "@/components/SelectDepartment";
import SelectTaskType from "@/components/Selects/SelectTaskType";
import SelectLanguage from "@/components/Selects/SelectLanguage/index.vue";

const emits = defineEmits(["query"]);
const props = defineProps({
  options: {
    type: Object,
    required: true,
  },
});

const defaultProps = {
  children: "son",
  label: "name",
  value: "id",
  checkStrictly: false,
  multiple: true,
};

const data = reactive({
  form: {},
  visible: false,
  loading: false,
  formRef: null,
  rules: {
    tag_name: [{ required: true, message: "请输入标签名称", trigger: "change" }],
    tag_type: [{ required: true, message: "请选择标签类型", trigger: "blur" }],
    permissions_type: [{ required: true, message: "请选择标签权限", trigger: "blur" }],
    tag_color: [{ required: true, message: "请选择标签颜色", trigger: "blur" }],
  },
  shopOptions: [],
  handleType: "",
  load: false,
});

const { rules, form, visible, loading, formRef, shopOptions, handleType, load } = toRefs(
  data
);
const open = async (type, id) => {
  if (!load.value) {
    load.value = true;
    await 1;
  }
  handleType.value = type;
  form.value.auto_relation = {};
  if (id) await getDetail(id);
  form.value.tag_status = 1;
  form.value.tag_color = "#9C9C9C";
  visible.value = true;
};

const getDetail = async (id) => {
  try {
    const res = await getImagesTagDetail({ id });
    form.value = res.data;
    if (handleType.value == "copy") {
      delete form.value.id;
    }
  } catch (e) {
    throw Error(e);
  }
};

const changeType = async (val) => {
  if (val == 1) {
    form.value.auto_relation = {};
  }
  if (val == 2) {
    form.value.is_auto_relation = 1;
  }
  form.value.language_id = "";
  form.value.language_code = "";
};

const save = () => {
  if (!formRef.value) return;
  formRef.value.validate((valid) => {
    if (valid) {
      const formData = Object.assign({}, form.value);
      if (formData.tag_type == 4 && !formData.image_task_type_id) {
        return ElMessage.error("请输入任务类型ID");
      }
      if (formData.is_auto_relation && !formData.auto_relation.rule_type) {
        ElMessage.error("请选择角色类型");
        return;
      }
      if (areAllValuesEmpty(formData.auto_relation)) {
        formData.auto_relation = {};
      }

      if (formData.depart_ids?.length) {
        formData.permissions_depart_ids = Array.from(new Set(formData.depart_ids.flat()));
      } else {
        formData.permissions_depart_ids = [];
      }

      loading.value = true;
      if (formData.id) {
        editImagesTag(formData)
          .then((res) => {
            ElMessage.success(res.message);
            emits("query");
            close();
          })
          .finally(() => {
            loading.value = false;
          });
      } else {
        createImagesTag(formData)
          .then((res) => {
            ElMessage.success(res.message);
            emits("query");
            close();
          })
          .finally(() => {
            loading.value = false;
          });
      }
    }
  });
};

const areAllValuesEmpty = (obj) => {
  for (const key in obj) {
    if (obj.hasOwnProperty(key) && obj[key] !== "") {
      return false;
    }
  }
  return true;
};

const initForm = () => {
  form.value = getForm();
  shopOptions.value = [];
};

// 初始化
const getForm = () => {
  return {
    importer_id: "",
    platform_id: "",
    platform_name: "",
    store_id: null,
    store_name: [],
    site: null,
    remark: "",
    status: 1,
    country_id: "",
    country_name: "",
    base_importer: {},
  };
};

onMounted(() => {
  initForm();
});

const close = () => {
  initForm();
  visible.value = false;
};

const changePerson = (val) => {
  console.log(val);
};

const changePermissionsType = () => {
  form.value.images_tag_permissions = [];
  form.value.depart_ids = [];
  form.value.permissions_depart_ids = [];
};

const changeLanguage = (val) => {
  form.value.language_code = val;
};

defineExpose({ open });
</script>
<style lang="scss">
.label-color {
  .el-radio__input {
    display: none !important;
  }
}

.m-0 {
  margin: 0 !important;
}
</style>
